//
//  HamatonSettingViewController.swift
//  hamaton-app
//
//  Created by intyt on 2024/4/9.
//  接收机设置

import UIKit
import SnapKit
import Toast_Swift

class HamatonCarSettingViewController: HamatonBaseViewController {
    
    let deviceModel: DeviceSettingCellModel?
    
    weak var delegate: SecondViewControllerDelegate?

    public var addModel: HamatonCarSettingViewModel = HamatonCarSettingViewModel()
    
    init(deviceModel: DeviceSettingCellModel?) {
        self.deviceModel = deviceModel
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var addView: HamatonCarSettingView = {
        let topV = HamatonCarSettingView(frame: .zero)
        topV.delegate = self
        view.addSubview(topV)
        return topV
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        navigationItem.title = "接收机设置"
        addView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        addView.deviceModel = self.deviceModel
        if deviceModel != nil {
            addModel.carTypeModel = deviceModel?.carTypeModel
            addModel.communicationTypeModel = deviceModel?.communicationTypeModel
            addModel.CANCommunicationBaudRateModel = deviceModel?.CANCommunicationBaudRateModel
            addModel.CANTerminalResistanceModel = deviceModel?.CANTerminalResistanceModel ?? ""
            addModel.CANMailingAddressModel = deviceModel?.CANMailingAddressModel
            addModel.PCTRFChannel1Model = deviceModel?.PCTRFChannel1Model
            addModel.PCTRFChannel2Model = deviceModel?.PCTRFChannel2Model
            addModel.NumberOfTrailersModel = deviceModel?.NumberOfTrailersModel
            addModel.temperatureCompensationModel = deviceModel?.temperatureCompensationModel ?? ""
        }
        
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension HamatonCarSettingViewController: HamatonCarSettingViewDelegate {
    func hamatonCarSettingViewClickSwitch(tag: Int, type: Int) {
        if type == 1 { // CAN终端电阻 00 开启 01 关闭
            addModel.CANTerminalResistanceModel = tag == 0 ? "ON" : "OFF"
        } else if type == 2 { // 温度补偿 00 关闭 01开启
            addModel.temperatureCompensationModel = tag == 0 ? "OFF" : "ON"
        }
    }
    
    func hamatonCarSettingViewTextFieldChange(text: String?, type: Int) {
//        if type == 1 {
//            addModel.name = text ?? ""
//        }else {
//            addModel.phoneNum = text ?? ""
//        }
    }
    
    func hamatonCarSettingViewSelectedClick(type: Int) {
        if type == 1 {
            let vc: HamatonCarSettingSelectViewController = HamatonCarSettingSelectViewController()
            vc.selectTypeEnumFun(selectTypeEnum: .a)
            weak var weakSelf = self
            vc.backAction = {  (model: HamatonCarModel) -> Void in
                weakSelf?.addModel.carTypeModel = model
                weakSelf?.addView.carTypeModel = model
            }
            self.navigationController?.pushViewController(vc, animated: false)
        } else if type == 2 {
            let vc: HamatonCarSettingSelectViewController = HamatonCarSettingSelectViewController()
            vc.selectTypeEnumFun(selectTypeEnum: .b)
            weak var weakSelf = self
            vc.backAction = {  (model: HamatonCarModel) -> Void in
                weakSelf?.addModel.communicationTypeModel = model
                weakSelf?.addView.communicationTypeModel = model
            }
            self.navigationController?.pushViewController(vc, animated: false)
        } else if type == 3 {
            let vc: HamatonCarSettingSelectViewController = HamatonCarSettingSelectViewController()
            vc.selectTypeEnumFun(selectTypeEnum: .c)
            weak var weakSelf = self
            vc.backAction = {  (model: HamatonCarModel) -> Void in
                weakSelf?.addModel.CANCommunicationBaudRateModel = model
                weakSelf?.addView.CANCommunicationBaudRateModel = model
            }
            self.navigationController?.pushViewController(vc, animated: false)
        } else if type == 4 {
            let vc: HamatonCarSettingSelectViewController = HamatonCarSettingSelectViewController()
            vc.selectTypeEnumFun(selectTypeEnum: .d)
            weak var weakSelf = self
            vc.backAction = {  (model: HamatonCarModel) -> Void in
                weakSelf?.addModel.CANMailingAddressModel = model
                weakSelf?.addView.CANMailingAddressModel = model
            }
            self.navigationController?.pushViewController(vc, animated: false)
        } else if type == 5 {
            let vc: HamatonCarSettingSelectViewController = HamatonCarSettingSelectViewController()
            vc.selectTypeEnumFun(selectTypeEnum: .e)
            weak var weakSelf = self
            vc.backAction = {  (model: HamatonCarModel) -> Void in
                weakSelf?.addModel.PCTRFChannel1Model = model
                weakSelf?.addView.PCTRFChannel1Model = model
            }
            self.navigationController?.pushViewController(vc, animated: false)
        } else if type == 6 {
            let vc: HamatonCarSettingSelectViewController = HamatonCarSettingSelectViewController()
            vc.selectTypeEnumFun(selectTypeEnum: .f)
            weak var weakSelf = self
            vc.backAction = {  (model: HamatonCarModel) -> Void in
                weakSelf?.addModel.PCTRFChannel2Model = model
                weakSelf?.addView.PCTRFChannel2Model = model
            }
            self.navigationController?.pushViewController(vc, animated: false)
        } else if type == 7 {
            let vc: HamatonCarSettingSelectViewController = HamatonCarSettingSelectViewController()
            vc.selectTypeEnumFun(selectTypeEnum: .g)
            weak var weakSelf = self
            vc.backAction = {  (model: HamatonCarModel) -> Void in
                weakSelf?.addModel.NumberOfTrailersModel = model
                weakSelf?.addView.NumberOfTrailersModel = model
            }
            self.navigationController?.pushViewController(vc, animated: false)
        }
    }
    // 设置接收机基本参数
    func hamatonCarSettingViewSaveClick() {
        if let message = self.addModel.jundgeIsSave() {
            self.view.makeToast(message, duration: 3.0, position: .center)
        } else {
            // 调用接口逻辑处理
//            let settingString = "30"+"发送类型"+"000500"+"车辆类型"+"5A"+"RF通道1"+"RF通道2"+"010000"+"CAN通讯波特率"+"CAN终端电阻"+"CAN地址"+"0C0800C201000A000000"
            let fasongleixing = CommunicationTypeOption2[self.addModel.communicationTypeModel?.name ?? "BLE未过滤"] ?? ""
            let cheliangleixing = self.addModel.carTypeModel?.id ?? ""
            let rftongdao1 = self.addModel.PCTRFChannel1Model?.id ?? ""
            let rftongdao2 = self.addModel.PCTRFChannel2Model?.id ?? ""
            let cantongxunbotelv = self.addModel.CANCommunicationBaudRateModel?.id ?? ""
            let canzhongduandianzu = self.addModel.CANTerminalResistanceModel == "ON" ? "00" : "01"
            let candizhi = String(format: "%02X", Int(self.addModel.CANMailingAddressModel?.id ?? "1")!) // 十进制转为十六进制
            let settingString1 = "30" + fasongleixing + "000500"
            let settingString2 = cheliangleixing + "5A"
            let settingString3 = rftongdao1 + rftongdao2 + "010000"
            let settingString4 = cantongxunbotelv + canzhongduandianzu + candizhi + "0C0800C201000A000000"
            let settingString = settingString1 + settingString2 + settingString3 + settingString4
            // 保存设置
            delegate?.saveDeviceSetting(settingString)
            self.view.makeToastActivity(.center)
            // 延时调用方法
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                self.view.hideToastActivity()
                self.view.makeToast("接收机参数设置成功", duration: 3.0, position: .center)
            }
            let trailernum = self.addModel.NumberOfTrailersModel?.id ?? "0"
            if (Int(trailernum)! > 0) { // 挂车数量大于零的话，保存基本参数的同时保存挂车数量
                setTrailerNumFun()
            }
        }
    }
    // 设置挂车数量
    func setTrailerNumFun() {
        let guacheshuliang = self.addModel.NumberOfTrailersModel?.id ?? ""
        let settingString = "420" + String(guacheshuliang) + "0305032800013C000801FFB400000000000000"
        let carNum = String(guacheshuliang)
        delegate?.saveTrailerNum(settingString, carNum)
    }
    
    // 上下挂设置
    func goUpAndDownController(text: String) {
        if text == "0" {
            self.view.makeToast("至少选择一个挂车才能进行设置", duration: 3.0, position: .center)
        } else {
            self.view.makeToastActivity(.center)
            let vc = navigationController?.viewControllers.first(where: { $0 is HamatonDeviceViewController }) as? HamatonDeviceViewController
            vc?.navigateToViewController3()
            // 延时执行时间，单位为秒
            let delayInSeconds: TimeInterval = 2.0
            DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) {
                // 在延时之后清除提示
                self.view.hideToastActivity()
            }
            
        }
        
    }
}
